package com.cindata.api

import grails.converters.JSON
import groovy.json.JsonOutput
import groovyx.net.http.ContentType
import groovyx.net.http.FromServer
import groovyx.net.http.OkHttpBuilder
import okhttp3.OkHttpClient
import org.springframework.beans.factory.InitializingBean
import org.springframework.beans.factory.annotation.Value

import java.util.concurrent.TimeUnit

class EvaluationApiService implements InitializingBean
{

    static scope = "singleton"
    def http

    @Value('${evaluationApi.address}')
    String apiAddress
    @Value('${evaluationApi.context}')
    String apiContext
    @Value('${evaluationApi.key}')
    String apiKey
    @Value('${evaluationApi.manualEvaluate}')
    String manualEvaluateAPI
    /**
     * 自动评估
     * @param city 城市名
     * @param name 小区名
     * @return
     */
    def manualEvaluation(Map map)
    {
        post(manualEvaluateAPI, map)
    }

    @Override
    void afterPropertiesSet() throws Exception
    {
        http = OkHttpBuilder.configure {
            request.uri = apiAddress
            client.clientCustomizer { OkHttpClient.Builder builder -> builder.connectTimeout(10, TimeUnit.SECONDS)
            }
        }
    }

    def post(String url, Map data)
    {
        try
        {
            http.post {
                request.uri.path = "${apiContext}${url}"
                request.uri.query = [key: apiKey]
                request.contentType = ContentType.JSON
                if (data)
                {
                    request.body = data
                }
                log.info("--------------------->准备EvaluateAPI请求，地址：${request.uri.path},key：${request.uri.query}")
                log.info("--------------------->准备EvaluateAPI请求，参数：${JsonOutput.toJson(request.body).toString()}")
                response.parser("application/json")
                response.success { FromServer resp, json ->
                    println resp.statusCode
                    return JSON.parse(json.toString())
                }
                response.failure { resp ->
                    println resp.statusCode
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }

    def get(String url, Map data)
    {
        try
        {
            http.get {
                request.uri.path = "${apiContext}${url}"
                request.uri.query = [key: apiKey]
                request.contentType = ContentType.JSON
                data?.each { key, value -> request.uri.query[key] = value
                }
                response.parser("application/json")
                response.success { FromServer resp, json ->
                    println resp.statusCode
                    return JSON.parse(json.toString())
                }
                response.failure { FromServer resp ->
                    println resp.statusCode
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }
}
